<?php

namespace app\controller\admin;

use app\BaseController;
use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\export\OrdersExport;
use app\model\Notify;
use app\model\OrderLogs;
use app\model\Orders;
use app\model\Shops;
use app\model\ShopsPayment;
use Carbon\Carbon;
use Dcat\EasyExcel\Excel;
use think\facade\View;
use think\helper\Str;
use think\Request;

class OrderController extends BaseController
{
    public function index()
    {
        $shopList = Shops::query()->where('status',ModelConstant::STATUS_ON)->field(['id','name'])->select()->toArray();
        $orderStatus = Orders::$orderStatus;
        View::assign(['title'=>'订单列表',
            'shopList'=>$shopList,
            'paymentList'=>ShopsPayment::$payMethodNames,
            'orderStatus'=>$orderStatus
        ]);

        return View::fetch('admin/order_list');
        //return View::fetch('admin/test');
    }

    //
    public function getList(Request $request)
    {
        $isExport = $request->param('is_export',0);
        $builder = Orders::query()
               //订单编号
                ->when($request->has('last_order_name') && !empty($request->param('last_order_name')),function ($q) use ($request){
                    return $q->where('last_order_name','like',trim($request->param('last_order_name')) . '%');
                })
            //草稿订单
            ->when($request->has('name') && !empty($request->param('name')),function ($q) use ($request){
                return $q->where('name','like',trim($request->param('name')) . '%');
            })

            //店铺
            ->when($request->has('pay_method') && !empty($request->param('pay_method')),function ($q) use ($request){
                $paymentIds = ShopsPayment::query()->where('pay_method',$request->param('pay_method'))->column('id');
                return $q->whereIn('payment_id',$paymentIds);
            })
            //支付方式
            ->when($request->has('shop_id') && !empty($request->param('shop_id')),function ($q) use ($request){
                return $q->where('shop_id',$request->param('shop_id'));
            })
            //状态
            ->when($request->has('order_status') && !empty($request->param('order_status')),function ($q) use ($request){
                return $q->where('order_status',$request->param('order_status'));
            })
            //CN时间
            ->when($request->has('created_at') && !empty($request->param('created_at')),function ($q) use ($request){
                $created_at = $request->param('created_at');
                $created_at = explode('-',$created_at);
                $dateTime = [Carbon::parse($created_at[0])->startOfDay()->timestamp,Carbon::parse($created_at[1])->endOfDay()->timestamp];
                return $q->whereBetween('created_at',$dateTime);
            })
            //US时间
            ->when($request->has('us_at') && !empty($request->param('us_at')),function ($q) use ($request){
                $created_at = $request->param('us_at');
                $created_at = explode('-',$created_at);
                $start = Carbon::parse($created_at[0])->startOfDay()->timestamp;
                $end = Carbon::parse($created_at[1])->endOfDay()->timestamp;
//                $dateTime1 = [
//                    Carbon::parse($created_at[0])->tz(CommonConstant::US_TZ)->startOfDay()->timestamp,
//                    Carbon::parse($created_at[1])->tz(CommonConstant::US_TZ)->endOfDay()->timestamp
//                ];
                $dateTime = [
                    $start - CommonConstant::US_16_HOUR,
                    $end - CommonConstant::US_16_HOUR,
                ];
                //dd(compact('dateTime1','dateTime'));
                return $q->whereBetween('created_at',$dateTime);
            })
            ->order('created_int','DESC');
            $list = $builder->paginate(intval($request->param('limit',10)))->toArray();
            $list['count'] = $list['total'];
            $list['code'] = 0;
            $list['data'] = $this->formatOrderData($list['data']);
            return json($list);

    }

    protected function formatOrderData($data)
    {
        if(empty($data)) return [];
        $list = [];
        $shopList = Shops::query()->field(['id','name'])->select()->toArray();
        $shopList = array_column($shopList,'name','id');
        $paymentList = ShopsPayment::query()->field(['id','pay_method'])->select()->toArray();
        $paymentList = array_column($paymentList,'pay_method','id');
        foreach ($data as $item){
            $item['shop_name'] = $shopList[$item['shop_id']] ?? '-';
            $pay_method = $paymentList[$item['payment_id']] ?? 0;
            $item['pay_method'] = $pay_method == ShopsPayment::PAY_METHOD_PAYPAL ? '贝宝' : '信用卡';
            $item['last_order_name'] = Str::contains($item['last_order_name'],'#') ? $item['last_order_name'] : '-';
            //拆分订单
            $order = [
                'id'=>$item['id'],
                'shop_name'=>$item['shop_name'],
                'name'=>$item['name'],
                'last_order_name'=>$item['last_order_name'],
                'transaction_id'=>$item['transaction_id'],
                'total_price'=>$item['total_price'],
                'pay_method'=>$item['pay_method'],
                'order_status'=>$item['order_status'],
                'created_at'=>$item['created_at'],
                'created_date'=>$item['created_date'],
                'contact_email'=>$item['contact_email'],
            ];
            //加购
            $transaction_ids = explode(',',$item['transaction_id']);
            $orderNoArr = explode(',',$item['order_no']);
            if($pay_method == ShopsPayment::PAY_METHOD_PAYPAL){//贝宝
                $orderNoArr = array_filter($orderNoArr,function ($item){
                    return !Str::contains($item,'#');
                });
            }
            //订单拆分
            if(count($orderNoArr) > 1){
                for ($i = 0; $i < 2; $i++) {
                    $order['order_no'] = $orderNoArr[$i] ?? '-';
                    $order['transaction_id'] = $transaction_ids[$i] ?? '-';
                    $order['total_price'] = $i ? $item['repurchase_price'] : $item['total_price'];
                    $order['order_status'] = $i ? ($item['is_repurchase'] ? $item['order_status'] : Orders::ORDER_STATUS_FAIL) : $item['order_status'];
                    $list[] = $order;
                }
            }else{
                $list[] = $order;
            }
        }

        return $list;
    }

    public function show(Request $request,Orders $order)
    {
        $data = $order->toArray();
        $data['goodsList'] = $order->items()->field(['name','sku','quantity','price','image','variant_title'])->select()->toArray();
        $data['shippingLines'] = $order->shippings()->field(['title','price'])->select()->toArray();
        $data['shippingAddress'] = $order->shippingAddress->toArray();
        $data['billingAddress'] = $order->billingAddress->toArray();
        $data['customer'] = $order->customer->toArray();
        $data['title'] = "订单详情";
        $data['order_name'] = Str::contains($data['last_order_name'],'#') ? $data['last_order_name'] : $data['name'];
        $data['orderId'] = $data['order_id'] > 0 ? $data['order_id'] : pathinfo($data['admin_graphql_api_id'],PATHINFO_BASENAME);
        $data['created_at'] = Carbon::parse($data['created_at'])->format('Y年m月d日 H:i');
        $data['userLogs'] = OrderLogs::query()->where('checkout_id',$order->checkout_id)->field(['logs','created_at'])->select()->toArray();
        $requestLogs = Notify::query()->where('order_id',$order->id)->field(['params','created_at','pay_method'])->select()->toArray();
        foreach ($requestLogs as &$item){
            $item['pay_method'] = ShopsPayment::$payMethodNames[$item['pay_method']] ?? '-';
        }
        $data['requestLogs'] = $requestLogs;
        //dump(json_encode($data,JSON_UNESCAPED_SLASHES));
        //dd($data);
        return view('admin/order_detail',$data);
    }
}